import React, { memo,useCallback,useState,useEffect } from 'react'
import { Button,message,Modal } from "antd";
import { FullscreenOutlined,FullscreenExitOutlined ,ExclamationCircleOutlined} from "@ant-design/icons";
import { useDispatch,useSelector } from "react-redux";
import { withRouter } from "react-router-dom";
import moment from "moment";
import screenfull from 'screenfull'
import menuList from "@/common/menu_config";
import { deleteUserInfoAction } from "../../pages/login/store/actionCreator";
import { reqWeather } from "../../network";
import { HeaderWrapper } from "./style";

const { confirm } = Modal;

const HjHeader = memo(function (props) {
  // console.log(props);

  // state props
  const pathname = props.location.pathname
  const [isFull, setIsFull] = useState(false);
  const [date, setDate] = useState(moment().format('YYYY年MM月DD日, h:mm:ss'));
  const [weather, setWeather] = useState('');
  const [weather_icon, setWeather_icon] = useState('');
  const [temperature, setTemperature] = useState('');
  // redux hooks
  const dispatch = useDispatch() 
  const {user,title} = useSelector(state => ({
    user:state.userInfo.user,
    title:state.navTitle.title
  }))
 
  // other hooks 
  // 实时显示时间
  useEffect(() => {
    let timer = setInterval(() => {
        setDate(moment().format('YYYY年MM月DD日, h:mm:ss'))
      }, 1000);
    return () => {
      clearInterval(timer)
    };
  }, []);

  // 获取天气数据
  useEffect(() => {
    //  因为useEffect接收的是同步函数，写async会警告，所以在里面有定义一个函数
     async function requestData() {
        const res = await reqWeather()
        if(res.success!=='1')return;
        else{
          const {temperature_curr,weather,weather_icon} = res.result
          setWeather(weather)
          setTemperature(temperature_curr)
          setWeather_icon(weather_icon)
        }
      }
    requestData()
    
  }, []);
  // handle function
  // 解決刷新后，title為空的問題
  const findTitle = (menus)=>{
    let title =''
     menus.forEach(item=>{
        if(!item.children){
          if( item.path === pathname) title=item.title
        }else{
          const citen=  item.children.find(iten=>{
                return iten.path === pathname
            })
          if(citen) title = citen.title
        }
      })

      return title
  }
  
  // 切换全屏的回调
  const screenFull = useCallback(()=>{
    screenfull.toggle()
    setIsFull(!isFull)
  },[isFull])
  
  // 点击监听退出登录的回调
  const logout = useCallback(()=>{
    confirm({
    title: '确定退出登录吗？',
    icon: <ExclamationCircleOutlined />,
    content: '若退出需要重新登录',
    okText: '确认',
    cancelText: '取消',
    onOk() {
      dispatch(deleteUserInfoAction())
      message.success('成功退出！！！',1)
    },
  });
     
    //  console.log(props);
  },[dispatch])
 
  return (
    <HeaderWrapper>
      <div className="header-top">
        <div className="header-info">
          <Button type="dashed" size="small" onClick={screenFull}>{isFull?<FullscreenExitOutlined />:<FullscreenOutlined />}</Button>
          <span className="user">欢迎，{user.username}</span>
          <Button type="link" className="logout" onClick={logout}>退出</Button>
        </div>
      </div>
      <div className="header-bottom">
        <div className="left">{title|| findTitle(menuList)}</div>
        <div className="right">
          <span className="days">{date}</span>
          <img src={weather_icon} alt="天气信息" />
          <span className="weather">{weather} &nbsp; 温度：{temperature}</span>
        </div>
      </div>
    </HeaderWrapper>
  )
})


export default withRouter(HjHeader)